import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import forEach from "./forEach";
/**
 * 前序遍历，将树转换成映射
 * 每个返回节点会清空子节点，并设置额外的 [levelKey], [parentKey] 属性，但不改变原始数据
 * @param options
 * @returns
 */
var toMap = function toMap(treeNodes, options) {
  var _ref = options !== null && options !== void 0 ? options : {},
    _ref$uniqueKey = _ref.uniqueKey,
    uniqueKey = _ref$uniqueKey === void 0 ? 'key' : _ref$uniqueKey,
    _ref$levelKey = _ref.levelKey,
    levelKey = _ref$levelKey === void 0 ? 'level' : _ref$levelKey,
    _ref$childrenKey = _ref.childrenKey,
    childrenKey = _ref$childrenKey === void 0 ? 'children' : _ref$childrenKey,
    _ref$parentKey = _ref.parentKey,
    parentKey = _ref$parentKey === void 0 ? 'parentKey' : _ref$parentKey,
    _ref$level = _ref.level,
    level = _ref$level === void 0 ? 0 : _ref$level;
  var result = {};
  forEach(treeNodes, function (treeNode, _ref2) {
    var _objectSpread2;
    var parent = _ref2.parent,
      level = _ref2.level;
    if (!(uniqueKey in treeNode)) {
      throw new Error('please check unique key!');
    }
    if (result[treeNode[uniqueKey]]) {
      throw new Error('some tree-node has same unique key!');
    }
    var convertedNode = _objectSpread(_objectSpread({}, treeNode), {}, (_objectSpread2 = {}, _defineProperty(_objectSpread2, levelKey, level), _defineProperty(_objectSpread2, parentKey, parent === null || parent === void 0 ? void 0 : parent[uniqueKey]), _defineProperty(_objectSpread2, childrenKey, undefined), _objectSpread2));
    result[convertedNode[uniqueKey]] = convertedNode;
  }, {
    childrenKey: childrenKey,
    level: level
  });
  return result;
};
export default toMap;